package com.zhihao.takeaway.controller;

import com.zhihao.takeaway.common.utils.DateTool;
import com.zhihao.takeaway.common.utils.EasyUITable;
import com.zhihao.takeaway.common.utils.JwtUtil;
import com.zhihao.takeaway.common.utils.Result;
import com.zhihao.takeaway.entity.AddressBook;
import com.zhihao.takeaway.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/addressbook")
public class AddressBookController {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private AddressBookService addressBookService;

    @GetMapping
    public Result getAddressBookByUserId(){
        Result result = new Result();
        String UserId = getUserId();
        if(UserId == null || UserId.equals("")){
            result.fail("当前用户未登录");
        }else{
            EasyUITable easyUITable = addressBookService.getAddressBookByUserId(UserId);
            result.setData(easyUITable);
            result.success("成功获取下单地址列表");
        }
        return result;
    }
    @PostMapping("/save")
    public Result save(@RequestBody AddressBook addressBook){
        Result result = new Result();
        String UserId = getUserId();
        if(UserId == null || UserId.equals("")){
            result.fail("当前用户未登录");
        }else{
            addressBook.setIsDeleted(0);
            addressBook.setUpdateTime(DateTool.getCurrTime());
            addressBook.setCreateTime(DateTool.getCurrTime());
            boolean flag = addressBookService.save(addressBook);
            if(flag){
                result.success("添加成功");
            }else{
                result.fail("添加失败");
            }
        }
        return result;
    }

    public String getUserId(){
        String token = request.getHeader("token");
        String UserId = JwtUtil.validateToken(token);
        return UserId;
    }
}
